from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
import json
import time

# 导入Agent和Redis工具
from tools.logoAgent import logo_agent
from tools.myredis import mredis


@api_view(['POST'])
def generate_user_logo(request, user_id):
    """生成用户专属Logo的API视图 - 异步处理版本"""
    try:
        print(f"[AI视图] 开始处理Logo生成请求，用户ID: {user_id}")
        
        # 从自定义中间件获取用户信息
        user_info = getattr(request, 'user_info', None)
        if not user_info:
            print("[AI视图] 用户未登录")
            return Response({
                'success': False,
                'message': '未登录或登录已过期'
            }, status=status.HTTP_401_UNAUTHORIZED)
        
        # 从数据库获取用户信息
        from user.models import UserProfile
        from user.serializer import UserProfileSerializer

        try:
            user = UserProfile.objects.get(id=user_id)
            serializer = UserProfileSerializer(user)
            gender = serializer.data['gender']
            fitness_level = serializer.data['fitness_level']
        except UserProfile.DoesNotExist:
            print(f"[AI视图] 用户不存在，ID: {user_id}")
            return Response({
                'success': False,
                'message': '用户不存在'
            }, status=status.HTTP_404_NOT_FOUND)

        # 将请求添加到Redis队列
        request_data = {
            'user_id': user_id,
            'gender': gender,
            'fitness_level': fitness_level,
            'timestamp': time.time()
        }
        
        # 添加到队列
        mredis.list_push('logo_generation_queue', json.dumps(request_data))
        print(f"[AI视图] Logo生成请求已添加到队列，用户ID: {user_id}")
        
        return Response({
            'success': True,
            'message': 'Logo生成请求已提交，请稍后查询结果',
            'data': {
                'user_id': user_id,
                'status': 'processing',
                'message': 'Logo正在生成中，请稍后查询结果'
            }
        })

    except Exception as e:
        import traceback
        print(f"[AI视图] 发生异常: {str(e)}")
        print(f"[AI视图] 异常堆栈: {traceback.format_exc()}")
        return Response({
            'success': False,
            'message': f'提交Logo生成请求时发生错误: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def get_logo_generation_status(request, user_id):
    """查询Logo生成状态的API视图"""
    try:
        print(f"[AI视图] 查询Logo生成状态，用户ID: {user_id}")
        
        # 从自定义中间件获取用户信息
        user_info = getattr(request, 'user_info', None)
        if not user_info:
            print("[AI视图] 用户未登录")
            return Response({
                'success': False,
                'message': '未登录或登录已过期'
            }, status=status.HTTP_401_UNAUTHORIZED)
        
        # 从Redis查询结果
        result_key = f"logo_result_{user_id}"
        result_data = mredis.get(result_key)
        
        if result_data:
            try:
                result = json.loads(result_data)
                print(f"[AI视图] 找到Logo生成结果: {result}")
                
                # 如果成功，获取最新的用户数据
                if result.get('success'):
                    from user.models import UserProfile
                    from user.serializer import UserProfileSerializer
                    
                    try:
                        user = UserProfile.objects.get(id=user_id)
                        serializer = UserProfileSerializer(user)
                        result['user_data'] = serializer.data
                    except UserProfile.DoesNotExist:
                        result['message'] = '用户不存在'
                        result['success'] = False
                
                return Response(result)
                
            except json.JSONDecodeError:
                print(f"[AI视图] Redis中的结果数据格式错误")
                return Response({
                    'success': False,
                    'message': '结果数据格式错误'
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            print(f"[AI视图] 未找到用户 {user_id} 的Logo生成结果")
            return Response({
                'success': False,
                'message': 'Logo生成中，请稍后查询',
                'data': {
                    'user_id': user_id,
                    'status': 'processing'
                }
            }, status=status.HTTP_202_ACCEPTED)

    except Exception as e:
        import traceback
        print(f"[AI视图] 查询Logo状态时发生异常: {str(e)}")
        print(f"[AI视图] 异常堆栈: {traceback.format_exc()}")
        return Response({
            'success': False,
            'message': f'查询Logo生成状态时发生错误: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def get_logo_generation_progress(request, user_id):
    """查询Logo生成进度的API视图 - 用于HTTP轮询"""
    try:
        print(f"[AI视图] 查询Logo生成进度，用户ID: {user_id}")
        
        # 从自定义中间件获取用户信息
        user_info = getattr(request, 'user_info', None)
        if not user_info:
            print("[AI视图] 用户未登录")
            return Response({
                'success': False,
                'message': '未登录或登录已过期'
            }, status=status.HTTP_401_UNAUTHORIZED)
        
        # 从Redis查询进度
        progress_key = f"logo_progress_{user_id}"
        progress_data = mredis.get(progress_key)
        
        # 从Redis查询结果
        result_key = f"logo_result_{user_id}"
        result_data = mredis.get(result_key)
        
        response_data = {
            'user_id': user_id,
            'timestamp': time.time()
        }
        
        # 如果有进度信息
        if progress_data:
            try:
                progress_info = json.loads(progress_data)
                response_data.update(progress_info)
                print(f"[AI视图] 找到Logo生成进度: {progress_info}")
            except json.JSONDecodeError:
                print(f"[AI视图] Redis中的进度数据格式错误")
                response_data.update({
                    'status': 'error',
                    'message': '进度数据格式错误',
                    'progress': 0
                })
        
        # 如果有结果信息
        if result_data:
            try:
                result_info = json.loads(result_data)
                response_data['result'] = result_info
                print(f"[AI视图] 找到Logo生成结果: {result_info}")
                
                # 如果任务完成，返回成功状态
                if result_info.get('success') is not None:
                    return Response({
                        'success': True,
                        'data': response_data
                    })
                    
            except json.JSONDecodeError:
                print(f"[AI视图] Redis中的结果数据格式错误")
                response_data['result'] = {
                    'success': False,
                    'message': '结果数据格式错误'
                }
        
        # 如果没有进度和结果信息，说明任务还未开始
        if not progress_data and not result_data:
            response_data.update({
                'status': 'waiting',
                'message': '任务等待中...',
                'progress': 0
            })
        
        return Response({
            'success': True,
            'data': response_data
        })

    except Exception as e:
        import traceback
        print(f"[AI视图] 查询Logo进度时发生异常: {str(e)}")
        print(f"[AI视图] 异常堆栈: {traceback.format_exc()}")
        return Response({
            'success': False,
            'message': f'查询Logo生成进度时发生错误: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)